<template>
  <div>
    <!--修改客户端授权信息-->
    <a-drawer
			:title="$t('Modify-client-info')" 
			width='40%' 
			:visible="visible"
			:body-style="drawerBodyStyle"
			@close="handleCancel"
			:maskClosable='false'
		>
    <!-- <a-spin size="large" style="position:absolute;left:50%; top:50%; transform: translate(-50%, -50%);z-index:1;background:rgba(255,255,255,.6);padding:10%" tip="Submit successfully Loading..." v-if="spinning == true"></a-spin> -->
      <a-form :form='form' :layout="formDirection">
        <!-- 基本信息 -->
				<div class="form-title">{{$t('Base_info')}}</div>
        <a-form-item :label="$t('Create')+'iSCSI '+$t('Client')" v-bind='formlayout'>
          <a-input disabled 
            v-decorator="['iqn',{
              rules:[
                // {required:true,message:$t('Enter')+$t('Client') + $t('Name')},
		  			    // {pattern:/^[a-zA-Z][0-9a-zA-Z-]{2,31}$/,message: $t('Not_enter_special_characters4')}
              ],
              // initialValue: targetClient.name && targetClient.name.substring(19)
              initialValue: targetClient.name && targetClient.name
            }]" 
            :placeholder="$t('Enter')+$t('Client') + $t('Name')" 
          ></a-input>
          <!-- :addonBefore="targetClient.name && targetClient.name.substring(0,19)" -->
        </a-form-item>
		  	<a-form-item label="target" v-bind="formlayout">
          <a-select 
            disabled 
            v-decorator="['target',{
              // rules:[{required:true,message:$t('Choose')+'target'}],
              initialValue: targetClient.target
            }]"  :placeholder="$t('Choose')+'target'"
          >
              <!-- <a-select-option v-for="i in basedata.targets" :value='i' :key="i">{{i}}</a-select-option> -->
          </a-select>
        </a-form-item>
        <!-- 启用chap认证 -->
        <div class="form-title">
					<a-checkbox :checked="chapChecked" @change="changeChapCheck">
						<span v-if="$store.state.language=='zh'">启用chap认证</span>
						<span v-else>Enable Chap Authentication</span>
					</a-checkbox>
				</div>
        <a-row :gutter="15" v-if="chapChecked">
          <a-col :span="12">
            <a-form-item :label="$t('User')+$t('Name')" v-bind='formlayout'>
              <a-input :disabled="isDisabledName" 
                v-decorator="['username',{
                  rules:[
                    {required:true,message:$t('Enter')+$t('User') + $t('Name')},
                    {pattern:/^[a-zA-Z][0-9a-zA-Z.:@_-]{7,63}$/,message: $t('Not_enter_special_characters2')}],
                    initialValue: targetClient.username
                  }]" :placeholder="$t('Enter')+$t('User') + $t('Name')"
                  @change="changeUsername"
                  style="width:85%"
              >
              </a-input>
              <a-tooltip placement='bottom' v-if="isDisabledName">
                <template slot='title'>
                    <span>{{$t('Edit')}}</span>
                </template>
                <!-- <i class="icon icon-edit16f edit-img-btn" @click="isDisabledName = !isDisabledName"></i> -->
                <Iconfont class="icon edit-img-btn" type="icon-edit16f" @click="isDisabledName = !isDisabledName"></Iconfont>
              </a-tooltip>
              <a-tooltip placement='bottom' v-else>
                <template slot='title'>
                    <span>{{$t('Save')}}</span>
                </template>
                <img @click="saveUsername" 
                        class="edit-img-btn"
                        src="../../../../../static/images/png/ic_save.png"
                        alt="save_img"
                />
              </a-tooltip>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('Password')" v-bind='formlayout'>
              <a-input-password :disabled="isDisabledPassword" v-decorator="['pwd',{
                rules:[
                  {required:true,message:$t('Enter') + $t('Password')},
                  {pattern:/^[0-9a-zA-Z@_/-]{12,16}$/,message: $t('Not_enter_special_characters3')}
                ],
                initialValue: targetClient.password
                }]"
                  :placeholder="$t('Enter') + $t('Password')"
                  style="width:85%"
                @change="changePassword"
              >
              </a-input-password>
              <a-tooltip placement='bottom' v-if="isDisabledPassword">
                <template slot='title'>
                  <span>{{$t('Edit')}}</span>
                </template>
                <!-- <i class="icon icon-edit16f edit-img-btn" @click="isDisabledPassword = !isDisabledPassword"></i> -->
                <Iconfont class="icon edit-img-btn" type="icon-edit16f" @click="isDisabledPassword = !isDisabledPassword"></Iconfont>
              </a-tooltip>
              <a-tooltip placement='bottom' v-else>
                <template slot='title'>
                  <span>{{$t('Save')}}</span>
                </template>
                <img @click="savePassword" 
                    class="edit-img-btn"
                    src="../../../../../static/images/png/ic_save.png"
                    alt="save_img"
                />
              </a-tooltip>
            </a-form-item>
          </a-col>
        </a-row>
        <!-- 启用双向认证 -->
        <div class="form-title">
					<a-checkbox :checked="twoWayChecked" @change="changeTwoWayCheck">
						<span v-if="$store.state.language=='zh'">启用双向认证</span>
						<span v-else>Enable Two-Way Authentication</span>
					</a-checkbox>
				</div>
        <a-row :gutter="15" v-if="twoWayChecked">
					<a-col :span="12">
						<a-form-item :label="$t('Reverse-user-name')" v-bind='formlayout'>
							<a-input 
								v-decorator="['reverse_username',{
									rules:[
										{required:true,message:$t('Enter')+$t('Reverse-user-name')},
										{pattern:/^[a-zA-Z][0-9a-zA-Z.:@_-]{7,63}$/,message: $t('Not_enter_special_characters2')}],
                  initialValue: targetClient.mutual_username && targetClient.mutual_username
									}]"
								:placeholder="$t('Enter')+$t('Reverse-user-name')">
							</a-input>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item :label="$t('Reverse-user-password')" v-bind='formlayout'>
							<a-input-password v-decorator="['reverse_pwd',{
								rules:[
									{required:true,message:$t('Enter') + $t('Reverse-user-password')},
									{pattern:/^[0-9a-zA-Z@_/-]{12,16}$/,message: $t('Not_enter_special_characters3')}
								],
                initialValue: targetClient.mutual_password && targetClient.mutual_password
                }]"
									:placeholder="$t('Enter') + $t('Reverse-user-password')">
							</a-input-password>
						</a-form-item>
					</a-col>
				</a-row>
        <!-- 其他 -->
				<div class="form-title">{{$t('Other')}}</div>
				<!-- 所属主机组 -->
        <a-form-item :label="$t('Host-group')" v-bind="formlayout">
					<a-spin :spinning="isLoadingHostGroup">
          <a-select 
						v-decorator="['host_group',{
              // rules:[{required:true,message:$t('Choose')+$t('Host-group')}]
              initialValue: targetClient.host_group ? targetClient.host_group : undefined
          	}]"
						:placeholder="$t('Choose')+$t('Host-group')"
            @change="changeHostGroup"
            allowClear
					>
						<a-select-option v-for="(host,index) in hostGroup" :value='host' :key="index">{{host}}</a-select-option>
          </a-select>
					</a-spin>
        </a-form-item>
        <!--配置lun-->
		  	<a-form-item v-if="!hostGroupValue" :label="$t('Config-lun')" v-bind='formlayout'>
          <a-spin :spinning="isLoadingForm">
		  		<a-transfer
		  			:data-source="lunData"
		  			:titles="[$t('Assign-lun'), $t('Selected-lun')]"
		  			show-search
		  			:filter-option="filterOption"
		  			:target-keys="targetKeys"
		  			:render="renderRowData"
		  			@change="handleChangeTransfer"
		  			:listStyle="{width:'45%',height:'350px'}"
		  			:locale="transferLocale"
            id="transferId"
		  		/>
          </a-spin>
		  		<!-- @search="handleSearch" -->
        </a-form-item>
      </a-form>
		  <div class="draw-bottom-btn">
		  	<a-button :style="{ marginRight: '8px' }" @click="handleCancel" style="width:80px">
		  		{{$t('Cancel')}}
		  	</a-button>
		  	<a-button type="primary" @click="handleEdit" :loading="isEditLoading" style="width:80px">
		  		{{$t('Sure')}}
		  	</a-button>
		  </div>
		</a-drawer>
  </div>
</template>

<script>

import request from '@/request/request'

export default {
  name: "EditClient",
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    targetClient: {
      type: Object,
      required: true,
      default: () => { return {} }
    },
    // basedata: {
    //   type: Object,
    //   required: true,
    //   default: () => { return {} }
    // },
    lunData: {
      type: Array,
      required: true,
    },
    isLoadingForm: {
			type: Boolean,
      required: true,
		}
  },
  data() {
    return {
      form: this.$form.createForm(this),
      formDirection: "vertical",
      formlayout:{
	      // labelCol:{span:6},
	      // wrapperCol:{span:18}
	    },
      // lunData: [],
			targetKeys: [],
			transferLocale: {
				itemUnit: '',
				itemsUnit: '',
				notFoundContent: this.$t('List-empty'),
				searchPlaceholder: this.$t('Enter-lun-or-pool')
			},
      isDisabledName: true,
      isDisabledPassword: true,
      isEditLoading: false,
      chapChecked: false,
			twoWayChecked: false,
      drawerBodyStyle: {
        paddingBottom: '50px !important',
      },
      currentUsername: '',
      changeUsernameValue: '',
      currentPassword: '',
      changePasswordValue: '',
      isLoadingHostGroup: false,
      hostGroupValue: '',
			hostGroup: []
    }
  },

  // mounted() {
    
  // },

  watch: {
    visible(newValue) {
      if(newValue) {
        // this.lunData = [];
        // if(this.basedata && this.basedata.blocks) {
        //   console.log('aaaa')
        //   this.basedata.blocks.forEach(item => {
        //     this.lunData.push({
        //       key: item,
        //       title: item
        //     })
        //   })
        // }
        this.targetKeys = this.targetClient.luns;
        this.initData();
      }
    }
  },

  methods: {
    // 初始化编辑的数据
    initData() {
      this.currentUsername = this.targetClient.username;
      this.currentPassword = this.targetClient.password;
      if(this.targetClient.mutual_username && this.targetClient.mutual_password) {
        this.twoWayChecked = true;
      }
      if(this.targetClient.username && this.targetClient.password) {
        this.chapChecked = true;
      }
      this.getUserGroupByTarget(this.targetClient.target)
    },

    changeUsername(e) {
      this.changeUsernameValue = e.target.value;
    },

    changePassword(e) {
      this.changePasswordValue = e.target.value;
    },

    saveUsername() {
      this.isDisabledName = !this.isDisabledName;
      this.currentUsername = this.changeUsernameValue;
    },

    savePassword() {
      this.isDisabledPassword = !this.isDisabledPassword;
      this.currentPassword = this.changePasswordValue;
    },

    // 通过target获取用户组
		async getUserGroupByTarget(target) {
			this.isLoadingHostGroup = true;
			const res = await this.$api.iscsi.getUserGroupByTargetRequest({target});
			// console.log('对应的主机组', res)
			if(res && res.data) {
				this.hostGroup = res.data.group;
			}
			this.isLoadingHostGroup = false;
		},

    //改变所属主机组
    changeHostGroup(value) {
      this.hostGroupValue = value;
    },

    //提交编辑客户端授权
    handleEdit(e) {
      e.preventDefault();
      this.form.validateFields((err,val)=>{
	      if(!err){
          // 是否有未保存的内容
          if(!this.isDisabledName || !this.isDisabledPassword) {
            const _this = this;
            this.$confirm({
              title: this.$store.state.language==='zh'?
              '你还有未保存的表单内容，将按原来未修改的值进行提交，是否继续？'
              :'You still have unsaved form content, which will be submitted with the original unmodified values. Do you want to continue?',
              // content: h => <div style="color:red;">Some descriptions</div>,
              okText: this.$t('Sure'),
              cancelText: this.$t('Cancel'),
              onOk() {
                _this.handleEditRequest(val);
              },
              onCancel() {
                // console.log('Cancel');
              },
            });
          }else {
            this.handleEditRequest(val);
          }
        }
      })
    },
    handleEditRequest(val) {
      this.isEditLoading = true;
      request('post', 'block/iscsi/update',{
				target: this.targetClient.target,
				iqn: this.targetClient.name.substring(0,19) + val.iqn,
				username: val.username,
				password: val.pwd,
				luns: val.host_group ? [] : this.targetKeys,
        mutual_username: this.twoWayChecked ? val.reverse_username : undefined,
				mutual_password: this.twoWayChecked ? val.reverse_pwd: undefined,
        host_group: val.host_group,
		  }).then(res=>{
        if(res.data.flag == 0) {
          //编辑成功后，更新表格数据
          this.$emit('editClientOk',{
            name: this.targetClient.name,
            username: this.currentUsername, // val.username
            password: this.currentPassword, // val.pwd
          })
        }else {
          this.model(res.data.id) //返回模板
          this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
        }
        this.form.resetFields();
      }).catch(err => {
        console.log(err);
      }).finally(() => {
        this.isEditLoading = false;
      })
    },

    //改变穿梭框选项
		handleChangeTransfer(targetKeys, direction, moveKeys) {
			// console.log(targetKeys, direction, moveKeys);
			this.targetKeys = targetKeys;
    },

		//穿梭框搜索
		filterOption(inputValue, option) {
			return option.title.indexOf(inputValue) > -1;
		},

		//渲染穿梭框的数据格式
		renderRowData(item) {
			return item.title
		},

    //取消抽屉显示
    handleCancel() {
      this.$emit('closeEditDrawer');
      this.chapChecked = false;
			this.twoWayChecked = false;
      this.form.resetFields();
    },

    //改变chap认证的选择状态
		changeChapCheck(e) {
			this.chapChecked = e.target.checked;
		},

		//改变双向认证的选择状态
		changeTwoWayCheck(e) {
			this.twoWayChecked = e.target.checked;
		},
  },
}
</script>
<style scoped>
  .draw-bottom-btn {
		/* float: right;
		padding-bottom: 20px; */
    position: absolute;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 4px 4px;
	}
  .edit-img-btn {
    color: var(--themeColor);
    margin-left: 8px;
    cursor: pointer;
  }
  .form-title {
		font-size: 14px;
		color: #333;
		margin-bottom: 10px;
    font-weight: 700;
	}
	.ant-form-vertical .ant-form-item {
		padding-bottom: 0;
	}
	::v-deep.ant-transfer-list-header {
		background: #e8e8e8;
	}
  /* 穿梭框标题位置互换 */
  ::v-deep#transferId .ant-transfer-list-header-selected > span:nth-child(1) {
    float: right;
  }
  ::v-deep#transferId .ant-transfer-list-header-selected > span:nth-child(2) {
    /* float: left; */
    position: relative;
    left: 0;
  }
</style>